/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.nb.common.utils;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.nutz.dao.Dao;

import com.nb.common.service.MonitorRealm.Principal;
import com.nb.system.model.User;


/**
 * 用户工具类
 */
public class UserUtils  {

	private static Dao dao = SpringContextHolder.getBean(Dao.class);

	public static User getUser(){
		Subject currentUser = SecurityUtils.getSubject();
		User user = (User)currentUser.getSession().getAttribute("currentUser");
		if(user==null){
			try{
				Subject subject = SecurityUtils.getSubject();
				Principal principal = (Principal)subject.getPrincipal();
				if (principal!=null){
					user = dao.fetch(User.class, principal.getId());
					
				}
			}catch (UnavailableSecurityManagerException e) {
				
			}catch (InvalidSessionException e){
				
			}
		}		
		if (user == null){
			user = new User();
			try{
				SecurityUtils.getSubject().logout();
			}catch (UnavailableSecurityManagerException e) {
				
			}catch (InvalidSessionException e){
				
			}
		}
		return user;
	}
	public static Principal getPrincipal(){
		Subject subject = SecurityUtils.getSubject();
		Principal principal = (Principal)subject.getPrincipal();
		return principal;
	}
	
//	public static User getUser2(){
//		User user = new User();
//		//User user = (User)getCache(CACHE_USER);
//		if (user == null){
//			try{
//				Subject subject = SecurityUtils.getSubject();
//				Principal principal = (Principal)subject.getPrincipal();
//				if (principal!=null){
//					user = userDao.get(principal.getId());
//				}
//			}catch (UnavailableSecurityManagerException e) {
//				
//			}catch (InvalidSessionException e){
//				
//			}
//		}
//		if (user == null){
//			user = new User();
//			try{
//				SecurityUtils.getSubject().logout();
//			}catch (UnavailableSecurityManagerException e) {
//				
//			}catch (InvalidSessionException e){
//				
//			}
//		}
//		return user;
//	}
	
	
}
